<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/1/17
 * Time: 14:04
 */

namespace app\common;


use app\common\model\Admin;
use app\common\model\Sellers;
use app\common\model\Users;
use think\Request;

class Session
{
    const KEY_USER_ID = "shop_user_id";

    static $user;

    /**
     * 获取当前用户
     * @return null|static|Users
     */
    static function get_local_user()
    {
        if (empty(self::$user)) {
            self::$user = Users::get(["id" => session(self::KEY_USER_ID)]);
        }
        return self::$user;
    }

    /**
     * 登录成功
     * @param Users $user
     * @return Users
     */
    static function login_success(Users $user)
    {
        $request = Request::instance();
        session(self::KEY_USER_ID, $user->id);
        $user->last_login_time = date("Y-m-d H:i:s");
        $user->last_login_ip = $request->ip();
        $user->token = md5(time() . rand(10000, 99999));
        $user->save();
        return self::$user = Users::get(["id" => session(self::KEY_USER_ID)]);
    }


    /**
     * 获取 当前商家
     * @var
     */
    static $seller;

    static function get_local_seller()
    {
        $user = self::get_local_user();
        $user_id = isset($user->id) ? $user->id : -1;
        if (empty(self::$seller)) {
            self::$seller = Sellers::get(["user_id" => $user_id]);
        }
        return self::$seller;
    }

    /**
     * 获取 当前商家
     * @var
     */
    static $admin;

    static function get_local_admin()
    {
        $user = self::get_local_user();
        $user_id = isset($user->id) ? $user->id : -1;
        if (empty(self::$admin)) {
            self::$admin = Admin::get(["user_id" => $user_id]);
        }
        return self::$admin;
    }


    static function logout()
    {
        session(self::KEY_USER_ID, null);
        return true;
    }

}